package viroyal.com.base.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.baidu.tts.client.model.DownloadHandler;
import com.suntiago.baseui.utils.ToastUtils;
import com.suntiago.baseui.utils.log.Slog;
import com.suntiago.network.network.Api;
import com.suntiago.network.network.BaseRspObserver;
import com.suntiago.network.network.ErrorCode;
import com.suntiago.network.network.utils.SPUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import viroyal.com.base.AppConfig;
import viroyal.com.base.R;
import viroyal.com.base.net.ApiObserver;
import viroyal.com.base.net.rsp.VersionAttributes;
import viroyal.com.base.net.rsp.VersionResponse;

import static android.content.Context.NOTIFICATION_SERVICE;
import static android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES;

/**
 * @author gaochao
 * 课堂app升级工具类
 */
@SuppressWarnings("ALL")
public class VersionUpdateHelper {
  public static final String TAG = VersionUpdateHelper.class.getSimpleName();

  private static final int UPDATE_NOTIFICATION_PROGRESS = 0x1;
  private static final int COMPLETE_DOWNLOAD_APK = 0x2;
  private static final int DOWNLOAD_NOTIFICATION_ID = 0x3;
  private static final int FAILED_DOWNLOAD_APK = 0x4;
  private static final String CURRENT_TIME = "current_time";
  private static final String VERSION_CODE = "version_code";
  private boolean isDownloading = false;

  private static final int CURRENT_ID = 0;

  private Context mContext;
  private NotificationManager notificationManager;
  private NotificationCompat.Builder ntfBuilder;
  private static String sPath;
  /**
   * 下载完成后的文件名后缀
   */
  private static final String SUFFIX = ".apk";
  /**
   * app名
   */
  private static final String APP_NAME = "APP_NAME";

  /**
   * 存放路径名和app的名字
   */
  private HashMap<String, String> cache = new HashMap<String, String>();

  /**
   * 是否自动安装
   */
  private boolean isAutoInstall;

  public VersionUpdateHelper(Context mContext, boolean isAutoInstall) {
    this.mContext = mContext;
    this.isAutoInstall = isAutoInstall;
    getApkPath(mContext);
  }

  public static String getApkPath(Context context) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      sPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    } else {
      SDCardUtils.StorageList storageList = new SDCardUtils.StorageList(context);
      sPath = storageList.getVolumePaths()[1];
    }
    return sPath + File.separator + AppConfig.APP_NAME
        + File.separator + AppConfig.APP_NAME
        + SUFFIX;
  }



  /**
   * 获取本地版本号
   *
   * @param context
   * @return
   */
  public static int getAppVersionCode(Context context) {
    try {
      String pName = context.getPackageName();
      PackageManager manager = context.getPackageManager();
      PackageInfo info = manager.getPackageInfo(pName, 0);
      int vCode = info.versionCode;
      return vCode;
    } catch (Exception e) {
      e.printStackTrace();
      return -1;
    }
  }
  /**
   * 对比网络版本做相应的需求操作
   *
   * @param activity 调用方的activity(继承自slothactivity)
   * @param isActive 是否采用策略
   */
  public void loadVersion(final Activity activity, boolean isActive, boolean showToast) {
    Slog.d(TAG, "loadVersion  [activity, isActive]:");
    //当前版本号
    final int version = getAppVersionCode(activity.getApplicationContext());
    Slog.i(TAG, "apk version = " + version);
    Api.get().getApi(ApiObserver.class)
        .getVersion()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new BaseRspObserver<VersionResponse>(VersionResponse.class, new Action1<VersionResponse>() {
              @Override
              public void call(VersionResponse rsp) {
                if (rsp.error_code == ErrorCode.SUCCESS) {
                  VersionAttributes versionAttributes = rsp.extra;
                  //如果有版本更新
                  //并且当前版本号低于网端版本号
                  if (versionAttributes != null
                      && Integer.parseInt(versionAttributes.version_code) > version) {

//                    SPUtils.getInstance(mContext).put(Settings.HAS_VERSION_UPDATE, true);
//                            if (isActive) {
//                              showUpdateUI(activity, versionAttributes);
//                            } else {
//                              //当前时间
//                              long currentTime = System.currentTimeMillis();
//                              //本地获取时间
//                              long time = SPUtils.getInstance(activity).get(CURRENT_TIME, 0L);
//                              //本地存储的版本号
//                              int homeVersion = SPUtils.getInstance(activity).get(VERSION_CODE, 0);
//                              long day = 24 * 60 * 60 * 1000L;//一天的时间
//                              //网端的版本号
//                              long netCode = Integer.parseInt(versionAttributes.version_code);
//                              //大于一天
//                              if ((currentTime - time) >= day
//                                      || homeVersion < netCode) {//或者本地存储版本号低于网端版本号
//                                //需要更新,刷新本地存储的版本号和时间
//                                SPUtils.getInstance(activity).put(CURRENT_TIME, currentTime);
//                                SPUtils.getInstance(activity).put(VERSION_CODE, netCode);
//                                //显示更新的对话框
//                                showUpdateUI(activity, versionAttributes);
//                              }
//                            }
                  } else {
//                    SPUtils.getInstance(mContext).put(Set tings.HAS_VERSION_UPDATE, false);
                    if (isActive && showToast) {
                      ToastUtils.showToast(activity, activity.getString(R.string.has_no_version_update));
                    }
                  }
                } else {
                  //错误处理
                  if (!TextUtils.isEmpty(rsp.error_msg) && showToast) {
                    ToastUtils.showToast(activity, rsp.error_msg);
                  }

                  Slog.e(TAG, "loadVersion: rsp is error" + rsp.error_code);
                }
              }
            }));
  }

}
